package com.djx.goods.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.djx.common.domain.Goods;
import com.djx.common.domain.User;
import com.djx.common.domain.request.GoodsRequest;
import com.djx.common.domain.response.GoodsResPonse;
import com.djx.common.result.Result;
import com.djx.goods.chush.GoodsChush;
import com.djx.goods.mapper.GoodsMapper;
import com.djx.goods.service.GoodsService;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private GoodsChush goodsChush;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private Redisson redisson;
    @Override
    public List<GoodsResPonse> getList(GoodsRequest goodsRequest) {
        List<GoodsResPonse> list=goodsMapper.getList(goodsRequest);
        goodsChush.chuSh();
        return list;
    }

    @Override
    public Goods findGoods(Integer id) {
        Goods goods=goodsMapper.findGoods(id);
        return goods;
    }

    @Override
    public void updateGoods(Goods goods) {
        RLock lock = redisson.getLock("goods");
        lock.lock();
        try {
            Goods findGoods = findGoods(goods.getId());
            if (goods.getNum()>findGoods.getNum()){
                throw new RuntimeException("库存不足");
            }
            goodsMapper.updateGoods(goods);

            String s = redisTemplate.opsForValue().get("user");
            User user = JSONObject.parseObject(s, User.class);
            if (goods.getPrice()>10){
                int jiFen= (int) (goods.getPrice()/10);
                user.setJifen(jiFen);
            }
            redisTemplate.opsForValue().set("user",JSONObject.toJSONString(user));
        } finally {
            lock.unlock();
        }
    }

    @Override
    public Result chouJiang() {
        String s = redisTemplate.opsForValue().get("user");
        User user = JSONObject.parseObject(s, User.class);
        if (user.getJifen()<2000){
            return Result.error("积分不足不够");
        }
        user.setJifen(user.getJifen()-2000);
        return Result.success("抽奖完成");
    }
}
